package week9

import (
	"bytes"
	"encoding/binary"
	"io"
)

func Decoder(r io.Reader) ([]byte, error) {
	var packHead []byte
	var err error

	packHead, err = ReadN(r, 6)

	packLenBuf := bytes.NewBuffer(packHead[0:4])

	var packLen int32

	err = binary.Read(packLenBuf, binary.BigEndian, &packLen)

	data, err := ReadN(r, packLen-6)

	var msg = make([]byte, packLen)
	copy(msg, packHead)
	copy(msg[6:], data)

	return msg, err

}

func ReadN(r io.Reader, n int32) ([]byte, error) {
	buf := make([]byte, n)
	_, err := io.ReadFull(r, buf)
	return buf, err
}
